#ifndef __TCP_CLIENT_HPP__
#define __TCP_CLIENT_HPP__
#include "MyPthread/Log.hpp"
#include "Common.hpp"
#include "InetAddr.hpp"
using namespace LogModule;

const static int gsockfd = -1;
class TcpClient
{
private:
public:
    TcpClient()
        : _sockfd(gsockfd), _server(server_ip, server_port)
    {
    }
    ~TcpClient()
    {
    }
    // 1. 创建socket
    void InitClient()
    {
        // 1. 创建socket
        _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::ERROR) << "socket error";
            Die(SOCKET_ERR);
        }
        // 2. 连接 
        // client 不需要显式地进行bind, tcp是面向连接的, connect 底层会自动进行bind
        int n = connect(_sockfd, _server.NetAddr(), _server.NetAddrLen());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "connect failed";
            Die(CONNECT_ERR);
        }
    }
    void Start()
    {

        while (true)
        {
            std::cout << "Please Enter# ";
            std::string message;
            std::getline(std::cin, message);

            int n = ::write(_sockfd, message.c_str(), message.size());
            (void)n;

            // LOG(LogLevel::DEBUG) << "send succeed:" << message;

            char inbuffer[1024];
            n = ::read(_sockfd, inbuffer, sizeof(inbuffer) - 1);
            if (n > 0)
            {
                inbuffer[n] = 0;
                std::cout << inbuffer << std::endl;
            }
        }
    }

public:
private:
    int _sockfd;
    // struct sockaddr_in _client;
    InetAddr _server;
};

#endif